package com.zoweunion.mechanic.controller.order;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.zoweunion.mechanic.controller.BaseController;
import com.zoweunion.mechanic.dao.app.AppDao;
import com.zoweunion.mechanic.model.ResponseBean;
import com.zoweunion.mechanic.model.User;
import com.zoweunion.mechanic.service.app.AppService;
import com.zoweunion.mechanic.service.app.OrderService;
import com.zoweunion.mechanic.service.order.CGOrderService;
import com.zoweunion.mechanic.service.order.KFOrderService;
import com.zoweunion.mechanic.util.*;
import com.zoweunion.mechanic.util.constants.Constants;
import com.zoweunion.mechanic.util.constants.PushConstants;
import com.zoweunion.mechanic.util.entity.OrderCheck;
import com.zoweunion.mechanic.util.task.PushTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 高管工单控制层
 *
 * @author Administrator
 */
@RestController
@RequestMapping("/cgOrder")
@SuppressWarnings("unchecked")
public class CGOrderController extends BaseController {

    @Autowired
    private AppDao appDao;

    @Autowired
    private CGOrderService cgOrderService;
    @Autowired
    private AppService appService;
    @Autowired
    private KFOrderService kFOrderService;
    @Autowired
    private JiGuangPushUtil jiGuangPushUtil;
    @Autowired
    private PushTask pushTask;
    @Autowired
    private OrderService orderService;

    /**
     * 获取待配件列表(分页,条件模糊,排序)
     *
     * @throws MyException
     */
    @PostMapping("/dpjList")
    public ResponseBean dtzList(@RequestBody String str, HttpServletRequest request) throws MyException {
        logBefore(logger, "仓管工单_待配件列表");
        Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
        User user = getCurrentUser(request);
        reqMap.put("s_id", getCurrentUser(request).getS_id());
        reqMap.put("order_statuses", new int[]{Constants.ORDER_STATUS_PJ, Constants.ORDER_STATUS_YTZ});
        reqMap.put("user", user);
        if (!Constants.ROLE_GLY.equals(user.getR_id())) {
//            reqMap.put("precinctRegions", String.join(",", appService.getPrecinctRegionNumbers(user.getId(), user.getS_id())));
            // 这里应该修改成该仓管所属仓库的管辖范围
//            String[] warehouseRegions = appService.getWarehouseRegions(user.getId());
//            reqMap.put("precinctRegions", String.join(",", warehouseRegions));
            // 修改成匹配订单所属仓库，有时候会不在仓库的管辖范围内
            // 该仓管的所属仓库id
            reqMap.put("warehouselocation_id",user.getWarehouse_id());
        }
        Map<String, Object> resultMap = cgOrderService.listByStatus(reqMap);
        logAfter(logger);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", resultMap);
    }

    /**
     * 获取待返仓列表(分页,条件模糊,排序)
     *
     * @throws MyException
     */
    @PostMapping("/dfcList")
    public ResponseBean dfcList(@RequestBody String str, HttpServletRequest request) throws MyException {
        logBefore(logger, "仓管工单_待返仓列表");
        Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
        User user = getCurrentUser(request);
        reqMap.put("s_id", getCurrentUser(request).getS_id());
        reqMap.put("rw_status", "2");
        reqMap.put("user", user);
        if (!Constants.ROLE_GLY.equals(user.getR_id())) {
            reqMap.put("precinctRegions", String.join(",", appService.getPrecinctRegionNumbers(user.getId(), user.getS_id())));
        }
        Map<String, Object> resultMap = cgOrderService.listByStatus(reqMap);
        logAfter(logger);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", resultMap);
    }


    /**
     * 获取历史工单列表(分页,条件模糊,排序)
     *
     * @throws MyException
     */
    @PostMapping("/cgHistoryList")
    public ResponseBean tzHistoryList(@RequestBody String str, HttpServletRequest request) throws MyException {
        logBefore(logger, "仓管工单_历史工单");
        Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
        User user = getCurrentUser(request);
        reqMap.put("user", user);
        reqMap.put("s_id", getCurrentUser(request).getS_id());
        //创建需要查询的状态数组
        int[] order_statuses = {Constants.ORDER_STATUS_DLL, Constants.ORDER_STATUS_YLL,
                Constants.ORDER_STATUS_QWXC, Constants.ORDER_STATUS_DDXC, Constants.ORDER_STATUS_QRFA, Constants.ORDER_STATUS_ZJ, Constants.ORDER_STATUS_HJ,
                Constants.ORDER_STATUS_WXJS, Constants.ORDER_STATUS_QRJS, Constants.ORDER_STATUS_DZF, Constants.ORDER_STATUS_QRSK, Constants.ORDER_STATUS_DPJ, Constants.ORDER_STATUS_WC,
                Constants.ORDER_STATUS_TZWC
        };
        reqMap.put("order_statuses", order_statuses);
        if (!Constants.ROLE_GLY.equals(user.getR_id())) {
            reqMap.put("precinctRegions", String.join(",", appService.getPrecinctRegionNumbers(user.getId(), user.getS_id())));
        }
        Map<String, Object> resultMap = cgOrderService.listByStatus(reqMap);
        logAfter(logger);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", resultMap);
    }


    /**
     * 仓管工单 获取工单详情 (待配件)
     *
     * @param str 包含 order_id
     */
    @PostMapping("/getOrderInfo")
    public ResponseBean getOrderInfo(@RequestBody String str, HttpServletRequest request) throws MyException {
        logBefore(logger, "仓管工单_获取工单详情");
        Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
        User user = getCurrentUser(request);
        reqMap.put("user_id", user.getId());
        Map<String, Object> resultMap = cgOrderService.getOrderInfo(reqMap);
        logAfter(logger);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", resultMap);
    }


    /**
     * 仓管工单 确认配件 (待配件>>待领料 6)
     *
     * @throws MyException
     */
    @PostMapping("/doParts")
    public ResponseBean doListen(@RequestBody String str, HttpServletRequest request) throws MyException {
        logBefore(logger, "听诊工单_听诊操作");
        Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
        reqMap.put("current_user_id", getCurrentUser(request).getId());
        reqMap.put("u_cg_id", getCurrentUser(request).getId());
        int result = kFOrderService.updateOrderInfo(reqMap);

        if (result > 0) {
            return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", null);
        }
        logAfter(logger);
        return new ResponseBean(Constants.CODE_HANDEL_FAILED, "操作失败", null);
    }

    /**
     * 仓管确认配件,后台将相应配件插入数据库,并且修改工单的状态
     *
     * @throws MyException
     */
    @SuppressWarnings("unchecked")
    @PostMapping("/addParts")
    public ResponseBean addParts(@RequestBody String str, HttpServletRequest request) throws MyException {
        logBefore(logger, "仓管确认配件,后台将相应配件插入数据库");

        //封装一个推送的map
        Map<String, Object> msgMap = new HashMap<>();
        Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
        //取登录信息
        User user = getCurrentUser(request);
        reqMap.put("current_user_id", user.getId());
        reqMap.put("s_id", user.getS_id());

        String current_user_id = user.getId();
        String order_id = reqMap.get("order_id").toString();
        String u_cg_id = user.getId();
        String rw_status = reqMap.get("rw_status").toString();
        reqMap.put("u_cg_id", u_cg_id);

        // 如果其他仓管已经处理，就不允许再处理了
        Map<String, Object> orderInfoMap1 = appDao.findOrderInfoById(reqMap);
        if(!orderInfoMap1.get("order_status").equals(5)){
            return new ResponseBean(Constants.CODE_HANDEL_FAILED,"该工单已在处理中",null);
        }

        //保养配件插入工单配件表
        if (null != reqMap.get("upkeepParts")) {

            //order_type typex 工单类型 as_status statusx 是否增减配件标识
            reqMap.put("p_type", reqMap.get("typex"));

            cgOrderService.insertzjParts(reqMap);
        }

        //插入领料响应
        try {
            //更新仓管完成配件时间
            OrderCheck checkByOrderId = orderService.selectCheckByOrderId(order_id,
                    u_cg_id, Constants.ORDER_CHECK_CG_PASTS_RESPONSE);

            if (checkByOrderId.getEndTime()==null) {
                orderService.updateKfEndTimeList(checkByOrderId.getId());
                //删除多余仓管响应
                orderService.deleteCgResponse(order_id, u_cg_id, Constants.ORDER_CHECK_CG_PASTS_RESPONSE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //维修配件插入工单配件表
        if (null != reqMap.get("repairParts")) {

            //order_type typex 工单类型 as_status statusx 是否增减配件标识
            reqMap.put("p_type", reqMap.get("typex"));

            cgOrderService.insertzjParts(reqMap);
        }

        //确认配件后更改工单的状态信息
        int result = cgOrderService.updateOrderStatus(reqMap);

        //先查询订单所属的区域
        Map<String, Object> orderInfoMap = kFOrderService.getOrderInfo(reqMap);
        String area = orderInfoMap.get("area").toString();
        String orderNo = orderInfoMap.get("order_no").toString();
        String orderEndNumber = orderNo.substring(orderNo.length() - 4);
        msgMap.put("msg", String.format(PushConstants.TEMPLATE_ORDER_XG_ACCEPT_ACCESSORIES, orderEndNumber));
        reqMap.put("order_id", order_id);
        //根据工单的id查询修工的id]
        List<String> xgIdList = kFOrderService.findXgId(reqMap);
        xgIdList.forEach(item -> {
            reqMap.put("type", 6);
            reqMap.put("alias", item);
            reqMap.put("msg", msgMap.get("msg"));
            jiGuangPushUtil.push(reqMap);
            try {

                //更新仓管完成配件时间
                OrderCheck checkByOrderId = orderService.selectCheckByOrderId(order_id,
                        u_cg_id, Constants.ORDER_CHECK_CG_PASTS_RESPONSE);

                //如果已经有了该orderId,userId,checkType的单子,那么就不再插入该数据
                if(orderService.isCheckTypeExist(checkByOrderId.getOrderId(),item,Constants.ORDER_CHECK_XG_RESPONSE) == 0){
                    //插入领料响应
                    orderService.insertTzOrderCheck(OrderCheck.builder()
                            .orderId(checkByOrderId.getOrderId())
                            .orderNo(checkByOrderId.getOrderNo())
                            .userId(item)
                            .roleType(Constants.ROLE_XG)
                            .orderCreateTime(checkByOrderId.getOrderCreateTime())
                            .checkType(Constants.ORDER_CHECK_XG_RESPONSE)
                            .build());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        //先获取所有角色为修工的列表
        List<Map<String, Object>> xgList = kFOrderService.findUserByRid(reqMap);
        //过滤所有符合区域的修工，并求出所有修工的id
//		List<String> xgIdList = xgList.parallelStream().filter(item ->{
//			int index = item.get("area").toString().indexOf("大区");
//			if (item.get("area").toString().substring(index).equals(area)){
//				return  true;
//			}else {
//				return  false;
//			}
//		}).map(item ->{
//			return  item.get("id").toString();
//		}).collect(Collectors.toCollection(ArrayList :: new));
        //推送消息给所有符合条件的修工
		/*xgIdList.forEach(item ->{
			reqMap.put("alias", item);
			reqMap.put("msg", msgMap.get("msg"));
			jiGuangPushUtil.push(reqMap);
		});*/
        if (result != 1) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "操作失败");
        }
        //确认配件后插入工单明细表相应的记录
        String uuid = UuidUtil.get32UUID();

        //appDao.updateOrderDetail(reqMap);
        int flag = cgOrderService.insertOrderDetail(order_id, uuid, getCurrentUser(request).getId());

        if (flag != 1) {
            throw new MyException(Constants.CODE_HANDEL_FAILED, "操作失败");
        }
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", null);
    }

    /**
     * 仓管工单 判断仓库配料是否充足(充足)
     *
     * @throws MyException
     */
    @PostMapping("/doenough")
    public ResponseBean doEnough() throws MyException {
        logBefore(logger, "仓库充足");
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", null);
    }

    /**
     * 仓管工单 判断仓库配料是否充足(不充足)
     *
     * @throws MyException
     */
    @SuppressWarnings("unchecked")
    @PostMapping("/doNoEnough")
    public ResponseBean doNoEnough(@RequestBody String str, HttpServletRequest request) throws MyException {
        logBefore(logger, "库存不足");
        Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
        //reqMap.put("current_user_id", getCurrentUser(request).getId());
        int result = cgOrderService.doNoEnough(reqMap);
        if (result != 1) {
            return new ResponseBean(Constants.CODE_HANDEL_FAILED, "操作失败", null);
        }
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", null);
    }

    /**
     * 刷新配件旧数据/上线后删除
     */
    @GetMapping("/refreshParts")
    public void refreshParts() {
        cgOrderService.refreshParts();
    }


    /**
     * 定时统计配件
     */
    @Scheduled(cron = "0 0 1 1/1 * ?")
    public void countParts() {
        cgOrderService.countParts();
    }

    /**
     * 配件统计查询
     *
     * @throws MyException
     */
    @GetMapping("/selectPartsCount")
    public ResponseBean selectPartsCount(@RequestParam Map<String, Object> map) {
        PageInfo<CGOrderEntity> entities = cgOrderService.selectPartsCount(map);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", entities);
    }

    /**
     * 定时统计工单异常
     */
    @Scheduled(cron = "0 0 1 1/1 * ?")
    @GetMapping("/orderException")
    public void orderException() {
        cgOrderService.orderException();
    }

    /**
     * 获取本月团队绩效指数
     */
    @GetMapping("/selectOrderCountHead")
    public ResponseBean selectOrderCountHead(@RequestParam Map<String, Object> map
            , HttpServletRequest request) throws MyException, ParseException {
        map.put("s_id", getCurrentUser(request).getS_id());
        OrderException objectMap = cgOrderService.selectOrderCountHead(map);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", objectMap);
    }

    /**
     * 异常工单列表 根据时间和分组维度
     */
    @GetMapping("/selectOrderByException")
    public ResponseBean selectOrderByException(@RequestParam Map<String, Object> map
            , HttpServletRequest request) throws MyException, ParseException {
        map.put("s_id", getCurrentUser(request).getS_id());
        PageInfo info = cgOrderService.selectOrderByException(map);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", info);
    }

    /**
     * 工单列表 根据时间
     */
    @GetMapping("/selectOrderByTime")
    public ResponseBean selectOrderByTime(@RequestParam Map<String, Object> map
            , HttpServletRequest request) throws MyException, ParseException {
        map.put("s_id", getCurrentUser(request).getS_id());
        PageInfo info = cgOrderService.selectOrderByTime(map);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", info);
    }

    /**
     * 员工列表页面
     */
    @GetMapping("/selectPercentByUser")
    public ResponseBean selectPercentByUser(@RequestParam Map<String, Object> map,
                                            HttpServletRequest request) throws MyException, ParseException {
        map.put("s_id", getCurrentUser(request).getS_id());
        Map<String, Object> map1 = cgOrderService.selectPercentByUser(map);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", map1);
    }

    /**
     * 更新超时配置
     */
    @PostMapping("/updateTimeOuTDeploy")
    public ResponseBean updateTimeOuTDeploy(@RequestBody TimeOutDeploy timeOutDeploy,
                                            HttpServletRequest request) throws MyException {
        timeOutDeploy.setSId(getCurrentUser(request).getS_id());
        cgOrderService.updateTimeOuTDeploy(timeOutDeploy);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", "");
    }

    /**
     * 插入推送级别
     */
    @PostMapping("/insertTimeOutLevel")
    public ResponseBean insertTimeOutLevel(@RequestBody TimeOutLevel timeOutLevel,
                                           HttpServletRequest request) throws MyException {
        timeOutLevel.setSid(getCurrentUser(request).getS_id());

        return cgOrderService.insertTimeOutLevel(timeOutLevel);
    }

    /**
     * 查询超时配置
     */
    @GetMapping("/selectTimeOuTDeploy")
    public ResponseBean selectTimeOuTDeploy(HttpServletRequest request) throws MyException {
        TimeOutDeploy timeOutLevel1 = cgOrderService.selectTimeOuTDeploy(TimeOutDeploy.builder()
                .sId(getCurrentUser(request).getS_id())
                .build());
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", timeOutLevel1);
    }

    /**
     * 查询推送级别
     */
    @GetMapping("/selectTimeOutLevel")
    public ResponseBean selectTimeOutLevel(HttpServletRequest request) throws MyException {
        List<TimeOutLevel> outLevels = cgOrderService.selectTimeOutLevel(TimeOutLevel.builder()
                .sid(getCurrentUser(request).getS_id())
                .build());
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", outLevels);
    }

    /**
     * 临时测试
     */
    @GetMapping("/selectTimeOutPushCron")
    public void selectTimeOutPushCron(HttpServletRequest request) {
        pushTask.timeOutPushCron();
    }

    /**
     * 将已有故障类型刷新到新表
     */
    @GetMapping("/selectDictionariesBy")
    public void selectDictionariesBy(HttpServletRequest request) {
        cgOrderService.selectDictionariesBy();
    }

    /**
     * 故障类型列表
     */
    @GetMapping("/selectDictionariesByList")
    public ResponseBean selectDictionariesByList(@RequestParam Map<String, Object> map,
                                     HttpServletRequest request) throws MyException {
        map.put("s_id", getCurrentUser(request).getS_id());
        //map.put("s_id", "9af0873379454fe886c365440f7b7f86");
        PageInfo info = cgOrderService.selectDictionariesByList(map);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", info);
    }

    /**
     * 新增更新故障类型
     */
    @PostMapping("/insertDictionaries")
    public ResponseBean insertDictionaries(@RequestBody DictionariesFault dictionariesFault,
                                                 HttpServletRequest request) throws MyException {
        dictionariesFault.setSid( getCurrentUser(request).getS_id());
        return cgOrderService.insertDictionaries(dictionariesFault);
    }

    /**
     * 删除故障类型
     */
    @PostMapping("/deleteDictionaries")
    public ResponseBean deleteDictionaries(@RequestBody DictionariesFault dictionariesFault,
                                           HttpServletRequest request) throws MyException {
        dictionariesFault.setSid( getCurrentUser(request).getS_id());
        cgOrderService.deleteDictionaries(dictionariesFault);
        return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", "");
    }

    /**
     * 配件删除临时接口
     */

    @GetMapping("/deleteTest")
    public void setCgOrderService (){
        cgOrderService.deleteTest();
    }

    /**
     * 临时更新卡特工时接口
     */
    @GetMapping("/updateKateWorkHour")
    public void updateKateWorkHour (){
        cgOrderService.updateKateWorkHour();
    }
}
